package com.slorgs.web.config

import com.alibaba.fastjson.JSON
import com.slorgs.business.common.Constant
import com.slorgs.business.utils.ThreadLocalUtil
import com.slorgs.business.utils.TokenUtil
import com.slorgs.infrastructure.dto.ResponseDTO
import com.slorgs.infrastructure.model.User
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpStatus
import org.springframework.util.StringUtils
import org.springframework.web.method.HandlerMethod
import java.io.IOException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

@Configuration
class WebAuthInterceptor {

    companion object {
        private val log = LoggerFactory.getLogger(WebAuthInterceptor::class.java)

        fun buildUser(map: Map<String, String>): User {
            val user = User()
            user.realName = map["realName"]
            user.role = map["role"]
            user.loginName = map["loginName"]
            return user
        }
    }

    @Value("\${token.expirationTime}")
    private val expirationTime: Long? = null

    @Throws(Exception::class)
    fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
        request.characterEncoding = "UTF-8"
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"))
        response.setHeader("Access-Control-Allow-Methods", request.method)
        response.setHeader("Access-Control-Max-Age", "3600")
        response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"))
        var token = request.getHeader("token")
        if (StringUtils.isEmpty(token) || token == "null") {
            returnMessage("用户未登陆，拒绝访问", response, HttpStatus.BAD_REQUEST.value())
            return true
        }
        val map: Map<String, String>
        try {
            if (token.contains("Deep")) {
                token = token.replace("XDeep", "")
            }
            map = TokenUtil.parseToken(token)
        } catch (e: Exception) {
            returnMessage("用户信息无效，请重新登陆", response, HttpStatus.BAD_REQUEST.value())
            return false
        }
        val timeOfUse = System.currentTimeMillis() - map["timeStamp"]!!.toLong()
        try {
            if (timeOfUse > (expirationTime?.times(60000) ?: 60000)) {  //1.判断 token 是否过期
                returnMessage("认证已过期，请重新登陆", response, HttpStatus.BAD_REQUEST.value())
                return false
            }
            ThreadLocalUtil.put("CURRENT_USER", buildUser(map))
//            if (!isAdmin(handler)) {
//                returnMessage("你没有权限访问", response, HttpStatus.NETWORK_AUTHENTICATION_REQUIRED.value())
//                return false
//            }
            //            request.setAttribute("requestId", UUID.randomUUID().toString());
//            String requestMethod = request.getMethod();
//            String queryString = request.getQueryString();
//            Map<String, String> param = new HashMap<>();
//            param.put("queryParam", queryString);
//            param.put("bodyParam", JSON.toJSONString(request.getParameterMap()));
//            param.put("method", requestMethod);
//            param.put("agent", request.getHeader("user-agent"));
//            request.setAttribute("paramRes", param);
        } catch (e: Exception) {
            log.error("系统异常...", e)
            returnMessage("认证系统异常", response, HttpStatus.INTERNAL_SERVER_ERROR.value())
            return false
        }
        return true
    }

//    private fun isAdmin(handler: Any): Boolean {
//        if (handler is HandlerMethod) {
//            val handlerMethod = handler
//            // 获取方法上的注解
//            var required: WebAuthAnnotation? = handlerMethod.getMethodAnnotation(WebAuthAnnotation::class.java)
//            // 如果方法上的注解为空 则获取类上的注解
//            if (null == required) {
//                required = handlerMethod.method.getDeclaredAnnotation(WebAuthAnnotation::class.java)
//            }
//            return if (null == required) {
//                true //如果都没有就说明不作限制
//            } else {
//                val user: User = ThreadLocalUtil.getUser() //如果有则校验用户类型，如果是操作员则拦截
//                user.getRole().equals("admin")
//            }
//        }
//        return false
//    }

    @Throws(IOException::class)
    private fun returnMessage(info: String, httpServletResponse: HttpServletResponse, httpStatus: Int) {
        val responseDTO = ResponseDTO()
        responseDTO.message = info
        responseDTO.code = httpStatus
        httpServletResponse.contentType = "text/json;charset=UTF-8"
        httpServletResponse.characterEncoding = "UTF-8"
        httpServletResponse.writer.print(JSON.toJSON(responseDTO))
        httpServletResponse.writer.flush()
        httpServletResponse.writer.close()
    }
}